package com.mchsdk.paysdk.bean;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mchsdk.open.ApiCallback;
import com.mchsdk.paysdk.activity.MCWapPayActivity;
import com.mchsdk.paysdk.activity.PTBPayResultActivity;
import com.mchsdk.paysdk.bean.UserReLogin.ReLoginCallback;
import com.mchsdk.paysdk.bean.pay.ZfbPay;
import com.mchsdk.paysdk.callback.SelectPTBTypeCallback;
import com.mchsdk.paysdk.callback.WFTWapPayCallback;
import com.mchsdk.paysdk.callback.WXCallback;
import com.mchsdk.paysdk.common.Constant;
import com.mchsdk.paysdk.dialog.DialogUtil;
import com.mchsdk.paysdk.dialog.MCTipDialog;
import com.mchsdk.paysdk.dialog.SelectPTBTypeDialog;
import com.mchsdk.paysdk.entity.DiscountPrice;
import com.mchsdk.paysdk.entity.GamePayTypeEntity;
import com.mchsdk.paysdk.entity.PTBPayResult;
import com.mchsdk.paysdk.entity.UserDiscountEntity;
import com.mchsdk.paysdk.entity.UserPTBInfo;
import com.mchsdk.paysdk.entity.WXOrderInfo;
import com.mchsdk.paysdk.http.hfbpay.PaymentInfo;
import com.mchsdk.paysdk.http.process.PTBPayProcess;
import com.mchsdk.paysdk.http.process.PayTypeProcess;
import com.mchsdk.paysdk.http.process.UserDiscountProcess;
import com.mchsdk.paysdk.http.process.UserPtbRemainProcess;
import com.mchsdk.paysdk.http.process.WFTOrderInfoProcess;
import com.mchsdk.paysdk.utils.DeviceInfo;
import com.mchsdk.paysdk.utils.MCHInflaterUtils;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.MCMoneyUtils;
import com.mchsdk.paysdk.utils.ToastUtil;

/**
 * paysdk3.0.3
 */

@SuppressLint("NewApi")
public class ChoosePayModel {
    private static final String TAG = "ChoosePayModel";

    private final int PAYTYPE_PTB = 0x00;
    private final int PAYTYPE_WX = 0x01;
    private final int PAYTYPE_ZFB = 0x02;
    // 选择的支付按钮
    private int selectType = PAYTYPE_ZFB;

    private Context context;
    private View view;
    private LinearLayout llWX, llZFB, llPTB;// 外层布局
    private Button btnPay, btnPtbPay;
    private CheckBox cb_ptb, cb_zfb, cb_wx;
    private TextView txtUserDiscount;

    // 用户平台币余额
    private String userPtbMoney = "";
    // 用户绑定平台币余额
    private String userBindPtbMoney = "";
    // 获取平台币信息提示框
    MCTipDialog mcTipDialog;
    // 平台币弹窗
    SelectPTBTypeDialog ptbPayDialog;

    private float buyGoodsDiscount;
    private DiscountPrice discountPrice;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.GAME_PAY_TYPE_SUCCESS:
                    handlerGamePayType((GamePayTypeEntity) msg.obj);
                    break;
                case Constant.GAME_PAY_TYPE_FAIL:
                    ToastUtil.show(context, (String) msg.obj);
                    break;
                case Constant.GET_USER_DISCOUNT_SUCCESS:
                    handlerUserDiscount((UserDiscountEntity) msg.obj);
                    break;
                case Constant.GET_USER_DISCOUNT_FAIL:
                    ToastUtil.show(context, (String) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    public ChoosePayModel(Context context, View view) {
        init(context, view);
        initView();
        initPay();
    }

    private void init(Context context, View view) {
        this.context = context;
        this.view = view;
    }

    private void initView() {
        llPTB = (LinearLayout) view.findViewById(idName("ll_ptb"));
        cb_ptb = (CheckBox) view.findViewById(idName("cb_ptb"));
        cb_ptb.setTag(PAYTYPE_PTB);
        llPTB.setTag(PAYTYPE_PTB);
        cb_ptb.setOnClickListener(payClickListener);
        llPTB.setOnClickListener(payClickListener);

        llZFB = (LinearLayout) view.findViewById(idName("ll_zfb"));
        cb_zfb = (CheckBox) view.findViewById(idName("cb_zfb"));
        cb_zfb.setTag(PAYTYPE_ZFB);
        llZFB.setTag(PAYTYPE_ZFB);
        cb_zfb.setOnClickListener(payClickListener);
        llZFB.setOnClickListener(payClickListener);

        llWX = (LinearLayout) view.findViewById(idName("ll_wx"));
        cb_wx = (CheckBox) view.findViewById(idName("cb_wx"));
        llWX.setTag(PAYTYPE_WX);
        cb_wx.setTag(PAYTYPE_WX);
        cb_wx.setOnClickListener(payClickListener);
        llWX.setOnClickListener(payClickListener);

        btnPay = (Button) view.findViewById(idName("btn_mc_pay"));
        btnPay.setVisibility(View.VISIBLE);
        btnPay.setOnClickListener(startPayListener);
        btnPtbPay = (Button) view.findViewById(idName("btn_mc_ptb_pay"));
        btnPtbPay.setVisibility(View.GONE);
        btnPtbPay.setOnClickListener(payClickListener);

        txtUserDiscount = (TextView) view.findViewById(idName("txt_mch_user_discount"));
        txtUserDiscount.setVisibility(View.GONE);

        TextView shopnameView = (TextView) view.findViewById(idName("tv_goodname"));
        TextView priceView = (TextView) view.findViewById(idName("textView5"));
        shopnameView.setText(ApiCallback.order().getProductName());
        priceView.setText(ApiCallback.order().getGoodsPriceYuan());

        ImageView payBack = (ImageView) view.findViewById(idName("iv_mch_pay_back"));
        payBack.setOnClickListener(payListener);
//		ImageView payItem = (ImageView) view.findViewById(idName("iv_mch_pay_item"));
//		payItem.setOnClickListener(payListener);
    }

    private void initPay() {
        buyGoodsDiscount = 10;
        UserDiscountProcess discountProcess = new UserDiscountProcess();
        discountProcess.post(mHandler);
    }

    //原价
    private String price = ApiCallback.order().getGoodsPriceYuan();
    //折扣价
    private String realPrice = price;

    private void handlerUserDiscount(UserDiscountEntity userDiscount) {

        if (0 != userDiscount.getDiscountType() && 10 != userDiscount.getDiscountNum()) {

            buyGoodsDiscount = userDiscount.getDiscountNum();
            realPrice = String.format("%.2f", Float.parseFloat(price) * buyGoodsDiscount / 10);
            String discountInfo = "折扣:--";
            if (1 == userDiscount.getDiscountType()) {
                discountInfo = "首冲折扣:" + userDiscount.getDiscountNum();
            } else if (2 == userDiscount.getDiscountType()) {
                discountInfo = "续冲折扣:" + userDiscount.getDiscountNum();
            }
            txtUserDiscount.setText(discountInfo);
            txtUserDiscount.setVisibility(View.VISIBLE);
        }
        discountPrice = new DiscountPrice();
        discountPrice.setPrice(price);
        discountPrice.setRealPrice(realPrice);

        PayTypeProcess payTypeProcess = new PayTypeProcess();
        payTypeProcess.post(mHandler);
    }

    private void handlerGamePayType(GamePayTypeEntity gamePayType) {
        if (null != gamePayType) {
            MCLog.w(TAG, gamePayType.toString());
            llZFB.setVisibility(gamePayType.isHaveZFB() ? View.VISIBLE : View.GONE);
            llWX.setVisibility(gamePayType.isHaveWX() ? View.VISIBLE : View.GONE);

            selectType = gamePayType.isHaveWX() ? PAYTYPE_WX : PAYTYPE_PTB;
            selectType = gamePayType.isHaveZFB() ? PAYTYPE_ZFB : PAYTYPE_PTB;

            selectPayType(selectType);
        }
    }

    private OnClickListener payListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            sendPayResult("-1");
            ((Activity) context).finish();
        }
    };

    private OnClickListener startPayListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            MCLog.w(TAG, "start pay");
            if (FlagControl.flag) {
                checkPay();
                FlagControl.flag = false;
            }
        }
    };

    private OnClickListener payClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            MCLog.w(TAG, "select pay type");
            if (v.getId() == btnPtbPay.getId()) {
                checkPtbPay();
            } else if (v.getId() == llPTB.getId() || v.getId() == cb_ptb.getId()) {
                selectType = PAYTYPE_PTB;
            } else if (v.getId() == llWX.getId() || v.getId() == cb_wx.getId()) {
                selectType = PAYTYPE_WX;
            } else if (v.getId() == llZFB.getId() || v.getId() == cb_zfb.getId()) {
                selectType = PAYTYPE_ZFB;
            }
            selectPayType(selectType);
        }
    };

    /**
     * 显示支付选择界面
     */
    @SuppressWarnings("deprecation")
    private void selectPayType(int selectPayType) {
        MCLog.w(TAG, "selectPayType:" + selectPayType);
        int dselect = context.getResources().getIdentifier("mch_choosepay_select", "drawable", context.getPackageName());
        int dunselect = context.getResources().getIdentifier("mch_choosepay_unselect", "drawable", context.getPackageName());

        cb_ptb.setBackgroundResource(dunselect);
        cb_zfb.setBackgroundResource(dunselect);
        cb_wx.setBackgroundResource(dunselect);
        btnPay.setVisibility(View.VISIBLE);
        btnPtbPay.setVisibility(View.GONE);

        btnPay.setText("立即支付");
        switch (selectPayType) {
            case PAYTYPE_ZFB:
                cb_zfb.setBackgroundResource(dselect);
                break;
            case PAYTYPE_WX:
                cb_wx.setBackgroundResource(dselect);
                break;
            case PAYTYPE_PTB:
                cb_ptb.setBackgroundResource(dselect);
                btnPay.setVisibility(View.GONE);
                btnPtbPay.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private void paySelect() {
        MCLog.w(TAG, "selectType = " + selectType);
        if (PAYTYPE_ZFB == selectType) {
            zfbPayProcess();
        } else if (PAYTYPE_WX == selectType) {
            wftPayProcess();
        }
    }

    // TODO 支付宝-------------start
    private void zfbPayProcess() {
        ZfbPay zfbPay = new ZfbPay((Activity) context);
        zfbPay.zfbPayProcess();
    }

    // TODO 微富通 支付请求------------------start
    private void wftPayProcess() {
//        ApiCallback.setWXPayCallback(wxPayResultListener);
        ApiCallback.setWFTWapPayCallback(mWFTWapPayCallback);
        WFTOrderInfoProcess wftProcess = new WFTOrderInfoProcess();
        wftProcess.setGoodsName(ApiCallback.order().getProductName());
        wftProcess.setGoodsPrice(ApiCallback.order().getGoodsPriceYuan());
        wftProcess.setGoodsDesc(ApiCallback.order().getProductDesc());
        wftProcess.setExtend(ApiCallback.order().getExtendInfo());
        wftProcess.setPayType("1");
        //角色名称
        wftProcess.setRoleName(ApiCallback.order().getRoleName());
        //服务器名称
        wftProcess.setServerName(ApiCallback.order().getServerName());
        wftProcess.post(cpHandler);
        showDialog("给微信下单...");
    }

    private WFTWapPayCallback mWFTWapPayCallback = new WFTWapPayCallback() {
        @Override
        public void onResult(String code) {
            MCLog.e(TAG, "fun # wftPayCallback code = " + code);
            if (code.equals("0")) {
                sendPayResult(code);
            } else {
                show("支付失败！");
            }
        }
    };

    // TODO 微富通 支付请求------------------end


    // TODO 聚宝云 支付请求------------------end
    // TODO 查找平台币余额------------------start

    /**
     * 获取用户平台币 ptbType 0是游戏币 1是绑定游戏币
     */
    private void queryUserPtbMoney() {
        showDialog("获取平台币信息..");
        new UserPtbRemainProcess().post(cpHandler);
    }

    OnClickListener closeListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            ptbPayDialog.dismissAllowingStateLoss();
        }
    };


    private void handlerPtbInfo(Object obj) {
        FlagControl.flag = true;
        UserPTBInfo userPtb = (UserPTBInfo) obj;
        userPtbMoney = String.format("%.2f", userPtb.getPtbMoney());
        userBindPtbMoney = String.format("%.2f", userPtb.getBindptbMoney());
        ptbPayDialog = new SelectPTBTypeDialog.Builder()
                .setTitle("平台币")
                .setPTB("平台币余额:" + userPtbMoney)
                .setPayPTB("应付款平台币数量:" + realPrice)
                .setBindPTB("绑定平台币余额:" + userBindPtbMoney)
                .setmmSelectPTBTypeCallback(selectPtbTypeCallback)
                .setmmCloseListener(closeListener)
                .show(context, ((Activity) context).getFragmentManager(), discountPrice);
    }

    // TODO 平台币余额------------------end

    // TODO 平台币支付请求------------------start
    public final void ptb_pay(String payType) {
        PTBPayProcess ptbpayProcess = new PTBPayProcess();
        ptbpayProcess.setGoodsName(ApiCallback.order().getProductName());
        ptbpayProcess.setGoodsPrice(ApiCallback.order().getGoodsPriceYuan());
        ptbpayProcess.setGoodsDesc(ApiCallback.order().getProductDesc());
        ptbpayProcess.setExtend(ApiCallback.order().getExtendInfo());
        ptbpayProcess.setCode(payType);
        ptbpayProcess.post(cpHandler);
        showDialog("正在交易...");
    }

    protected void handlerPTBPayResult(Object obj) {
        PTBPayResult ptbPayResult = (PTBPayResult) obj;
        dismisDialog();
        if (null != ptbPayResult && ptbPayResult.getReturn_status().equals("1")) {
            Bundle ptbBundle = new Bundle();
            if (isBind) {
                ptbBundle.putString("price", price);
            } else {
                ptbBundle.putString("price", realPrice);
            }
            ptbBundle.putString("productname", ApiCallback.order()
                    .getProductName());
            ptbBundle.putString("tradeno", ptbPayResult.getOrderNumber());
            Intent ptbIntent = new Intent(context, PTBPayResultActivity.class);
            ptbIntent.putExtras(ptbBundle);
            ((Activity) context).startActivity(ptbIntent);
            ((Activity) context).finish();
//            sendPayResult("0");
        } else {
            String tipStr = "支付失败";
            if (null != ptbPayResult
                    && !TextUtils.isEmpty(ptbPayResult.getReturn_msg())) {
                tipStr = ptbPayResult.getReturn_msg();
            }
            show(tipStr);
            sendPayResult("-1");
        }
    }

    private boolean isBind;
    // TODO 平台币支付请求------------------end

    private SelectPTBTypeCallback selectPtbTypeCallback = new SelectPTBTypeCallback() {

        @Override
        public void selectPTBPayType(View v, boolean isGameType) {
            MCLog.e(TAG, "fun#selectPtbTypeCallback  isGameType = "
                    + isGameType);
            isBind = isGameType;
            float price = Float.parseFloat(realPrice);
            if (isGameType) {
                float bindptb = MCMoneyUtils.priceToFloat(userBindPtbMoney);
                if ((bindptb - price) >= 0) {
                    ptb_pay("2");
                } else {
//					show("绑定平台币不足，请使用其它支付方式！");
                    DialogUtil.showAlert(context, "提示", "绑定平台币余额不足", context, "确定");
                }
            } else {
                float ptb = MCMoneyUtils.priceToFloat(userPtbMoney);
                if ((ptb - price) >= 0) {
                    ptb_pay("1");
                } else {
//					show("平台币不足，请使用其它支付方式！");
                    DialogUtil.showAlert(context, "提示", "平台币余额不足", context, "确定");
                }
            }
        }
    };

    /**
     * 发送支付结果
     */
    protected void sendPayResult(String payResultCode) {
        MCPayModel.Instance().getPck().callback(payResultCode);
        if (payResultCode.equals("0")) {
            ((Activity) context).finish();
        }
    }

    private void checkPay() {
        String sessionuid = PersonalCenterModel.getInstance().getUserId();
        if (!TextUtils.isEmpty(sessionuid)) {
            paySelect();
        } else {
            UserReLogin reLogin = new UserReLogin(context);
            reLogin.userToLogin(new ReLoginCallback() {
                @Override
                public void reLoginResult(boolean res) {
                    MCLog.e(TAG, "reLogin res = " + res);
                    if (res) {
                        paySelect();
                    } else {
                        show("请登录");
                    }
                }
            });
        }
    }

    private void checkPtbPay() {
        String sessionuid = PersonalCenterModel.getInstance().getUserId();
        if (!TextUtils.isEmpty(sessionuid)) {
            queryUserPtbMoney();
        } else {
            UserReLogin reLogin = new UserReLogin(context);
            reLogin.userToLogin(new ReLoginCallback() {
                @Override
                public void reLoginResult(boolean res) {
                    MCLog.e(TAG, "reLogin res = " + res);
                    if (res) {
                        queryUserPtbMoney();
                    } else {
                        show("请登录");
                    }
                }
            });
        }
    }


    PaymentInfo _paymentInfo;
    //	protected HeepayServiceHelper _heepayHelper;
    public Handler cpHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dismisDialog();
            switch (msg.what) {
                case Constant.WFT_ORDERINFO_SUCCESS:
                    dismisDialog();
                    boolean isWxAvaliable = DeviceInfo.isWeixinAvilible(context);
                    if (!isWxAvaliable) {
                        ToastUtil.show(context, "没有安装微信");
                        FlagControl.flag = true;
                        return;
                    }
                    WXOrderInfo wxOrderInfo= (WXOrderInfo) msg.obj;
                    Intent intent = new Intent(context, MCWapPayActivity.class);
                    intent.putExtra("WXOrderInfo", wxOrderInfo);
                    context.startActivity(intent);
                    break;
                case Constant.WFT_ORDERINFO_FAIL:
                    dismisDialog();
                    show("支付失败:" + msg.obj);
                    FlagControl.flag = true;
                    break;
                case Constant.PTB_MONEY_SUCCESS:
                    handlerPtbInfo(msg.obj);
                    break;
                case Constant.PTB_MONEY_FAIL:
                    show("获取平台币出现异常：" + msg.obj);
                    FlagControl.flag = true;
                    break;
                case Constant.PTB_PAY_SUCCESS:// 平台币支付
                    handlerPTBPayResult(msg.obj);
                    break;
                case Constant.PTB_PAY_FAIL:
                    show((String) msg.obj);
                    break;
                default:
                    break;

            }
        }
    };

    /**
     * 打开提示信息
     */
    private void showDialog(String message) {
        mcTipDialog = new MCTipDialog.Builder().setMessage(message).show(
                context, ((Activity) context).getFragmentManager());
    }

    ;

    /**
     * 关闭提示信息
     */
    private void dismisDialog() {
        if (null != mcTipDialog) {
            mcTipDialog.dismiss();
        }
    }

    private void show(String message) {
        ToastUtil.show(context, message);
        MCLog.e(TAG, message);
    }

    private int idName(String name) {
        return MCHInflaterUtils.getIdByName(context, "id", name);
    }

}
